//
//  RHBleDeviceSearchVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/3/25.
//

#import "RHBleDeviceSearchVC.h"
#import "RHBleScanCell.h"
#import "CBLECenterMnger.h"
#import "RHNavigationController.h"
#import <YYAnimatedImageView.h>
#import <YYImage/YYImage.h>
#import "RHLocalDeviceVC.h"
#import "RHNavgationView.h"
#import "RHBleCmdManager.h"

@interface RHBleDeviceSearchVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *bleArr;

@property (nonatomic, strong) NSTimer *scanTimeOut;

@property (nonatomic,strong) UIImageView *animateImg_1;

@property (nonatomic, strong) UIImageView *animateImg_2;

@property (nonatomic, strong) QMUILabel *countLab;

@property (nonatomic, strong) QMUIButton *searchBtn;

@property (nonatomic, assign) BOOL receiveMsg;

@property (nonatomic, strong) RHNavgationView *navgationView;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) MASConstraint *tableTopConstraint;
@end

@implementation RHBleDeviceSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationItem.title = @"蓝牙查找".rh_localized;
    self.receiveMsg = YES;
    [self setupUI];
    kWeakSelf;
    [CBLECenterMnger checkAuthState:^(CBManagerState state) {
        if(state == CBManagerStatePoweredOn){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf scanDevice];
            });
        }
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
        self.receiveMsg = YES;
    [CBLECenterMnger shareMnger].isManualDisconnect = YES;
    [[RHBleCmdManager shareMnger]removeAllCommand];
    [ProgressHUDManage hideTips];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.receiveMsg = NO;
    [self stopScan];
    [self stopSearchAnimation];

}

-(void)setupUI
{
    [CBLECenterMnger shareMnger];
    ADD_MESSAGE(BLEMSG_CENTER_POWERON,   msgForBLEPowerOn);
    ADD_MESSAGE(BLEMSG_CENTER_NEWPHERAL, msgForNewPheral);
    ADD_MESSAGE(BLEMSG_PHERAL_CONNECT_RST, msgForPheralConnect);
    ADD_MESSAGE(BLEMSG_PHERAL_DISCONNECT, msgForPheralReConnect:);
    
    kWeakSelf;
    self.navgationView = [[RHNavgationView alloc]initWithController:self];
    self.navgationView.backgroundColor = CMainColorGreen;
    self.navgationView.title = @"蓝牙查找".rh_localized;
    [self.navgationView setButtonTitleColor:UIColor.whiteColor];
    [self.view addSubview:self.navgationView];
    
    UIView *topView = kView;
    [self.view addSubview:topView];
    self.topView = topView;
    [topView setBackgroundColor:CMainColorGreen];
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.navgationView.mas_bottom);
    }];
    
    UIView *imgContentView = kView;
    [topView addSubview:imgContentView];
    [imgContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_offset(10);
        make.height.offset(kScaleW(220));
    }];
    
    _animateImg_1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_search_bg"]];
    _animateImg_1.contentMode = UIViewContentModeScaleAspectFit;
    [imgContentView addSubview:_animateImg_1];
    [_animateImg_1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(kScaleW(0));
        make.bottom.mas_offset(-30);
        make.height.equalTo(weakSelf.animateImg_1.mas_width);
        make.centerX.centerY.centerY.mas_offset(0);
    }];
    
    NSMutableArray *imgArr = [NSMutableArray array];
    for (int i = 1; i<=4; i++) {
//        NSString *path = [[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"ble_searching_%d",i] ofType:nil];
        UIImage *img =  [UIImage imageNamed:[NSString stringWithFormat:@"ble_searching_%d",i]];
        [imgArr addObject:img];
    }
    _animateImg_2 = [[UIImageView alloc]init];
    _animateImg_2.contentMode = UIViewContentModeCenter;
    _animateImg_2.animationImages = imgArr;
    _animateImg_2.animationDuration = 2;
    _animateImg_2.animationRepeatCount = CGFLOAT_MAX;
    [imgContentView addSubview:_animateImg_2];
    [_animateImg_2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(weakSelf.animateImg_1);
        make.centerX.centerY.equalTo(weakSelf.animateImg_1);
       
    }];
    
    UIView *titleView = kView;
    titleView.backgroundColor = UIColor.whiteColor;
    titleView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    titleView.layer.cornerRadius = 10;
    [self.view addSubview:titleView];
    QMUILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.text = @"设备列表".rh_localized;
    titleLab.textColor = kRGB(63, 68, 67);
    titleLab.font = kSYSTEMFONT(16);
    [titleView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.bottom.mas_offset(0);
    }];
    
    QMUILabel *countLab = [[QMUILabel alloc]init];
    countLab.text = [NSString stringWithFormat:@"%@:0",@"数量".rh_localized];
    countLab.textColor = kColorRGBA(63, 68, 67,0.8);
    countLab.font = kSYSTEMFONT(14);
    [titleView addSubview:countLab];
    self.countLab = countLab;
    [countLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLab.mas_right).offset(15);
        make.centerY.equalTo(titleLab);
    }];
    
    
    
    
    QMUIButton *searchBtn = [[QMUIButton alloc]init];
    [searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
    [searchBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    searchBtn.titleLabel.font = kSYSTEMFONT(16);
    [searchBtn setCornerRadius:8];
    self.searchBtn = searchBtn;
    [searchBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
        make.height.offset(50);
    }];
    [[searchBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        
//        RHLocalDeviceVC *deviceVC = [[RHLocalDeviceVC alloc]init];
//        deviceVC.title = [CBLECenterMnger shareMnger].curPheral.devName;
//        [weakSelf.navigationController pushViewController:deviceVC animated:YES];
//        return;
        [weakSelf scanDevice];
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:UIColor.whiteColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHBleScanCell class] forCellReuseIdentifier:@"RHBleScanCell"];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }

    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.equalTo(weakSelf.searchBtn.mas_top).offset(-10);
      weakSelf.tableTopConstraint = make.top.equalTo(topView.mas_bottom).offset(10);
    }];

    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.equalTo(self.tableView.mas_top);
        make.height.offset(40);
    }];
    
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImage:[UIImage imageNamed:@"nodata_icon_1"] titleStr:@"未找到设备".rh_localized detailStr:@"请确认设备已正常开启，并且蓝牙开关已打开".rh_localized];
}


- (void)scanDevice{
    if ([CBLECenterMnger BLEIsPowerOff] ) {
        return;
    }
    
    if(![CBLECenterMnger shareMnger].isScaning){
        [[CBLECenterMnger shareMnger].dataPherals removeAll];
        
        [self.tableView reloadData];
        //开始扫描外部蓝牙设备
        [self startScanPeripherals];
        [self.searchBtn setTitle:@"停止查找".rh_localized forState:UIControlStateNormal];
        [self startSearchAnimation];
    }else{
        [self stopScan];
        [self.searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
        [self stopSearchAnimation];
        
    }
    self.countLab.text = [NSString stringWithFormat:@"%@:%ld",@"数量".rh_localized,[CBLECenterMnger shareMnger].dataPherals.totalNums];
}

-(void)startSearchAnimation
{
    [_animateImg_1.layer removeAnimationForKey:@"rotationAnimation"];
    CABasicAnimation *rotateAnimate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotateAnimate.fromValue = @(0);
    rotateAnimate.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotateAnimate.duration = 1.5;
    rotateAnimate.cumulative = YES;
    rotateAnimate.repeatCount = MAXFLOAT;
    [_animateImg_1.layer addAnimation:rotateAnimate forKey:@"rotationAnimation"];
    [self.animateImg_2 startAnimating];
    
    [self beginSearchDevice];
    _tableView.ly_emptyView = nil;
}

-(void)stopSearchAnimation
{
   
    [_animateImg_1.layer removeAnimationForKey:@"rotationAnimation"];
    [self.animateImg_2 stopAnimating];
    self.animateImg_2.image = [UIImage imageNamed:@"ble_searching_4"];
    [self finishSearchDevice];
    
    if ([[CBLECenterMnger shareMnger].dataPherals totalNums] == 0) {
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImage:[UIImage imageNamed:@"nodata_icon_1"] titleStr:@"未找到设备".rh_localized detailStr:@"请确认设备已正常开启，并且蓝牙开关已打开".rh_localized];
    }else{
        _tableView.ly_emptyView = nil;
    }
}

-(void)finishSearchDevice
{
    kWeakSelf;
    [self.tableTopConstraint uninstall];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        weakSelf.tableTopConstraint = make.top.equalTo(weakSelf.navgationView.mas_bottom).offset(40);
    }];
    [self.tableView setNeedsLayout];
    [UIView animateWithDuration:0.3 animations:^{
       
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
        self.topView.backgroundColor = UIColor.whiteColor;
        [self.navgationView setButtonTitleColor:UIColor.blackColor];
        self.navgationView.backgroundColor = UIColor.whiteColor;
    }];
    
}

-(void)beginSearchDevice
{
    kWeakSelf;
    [self.tableTopConstraint uninstall];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        weakSelf.tableTopConstraint = make.top.equalTo(weakSelf.topView.mas_bottom).offset(10);
    }];
    
   [self.tableView setNeedsLayout];
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
       
    }];
    
    self.navgationView.backgroundColor = CMainColorGreen;
    [self.navgationView setButtonTitleColor:UIColor.whiteColor];
    self.topView.backgroundColor = CMainColorGreen;
}


#pragma mark - 扫描定时器
- (void)startScanPeripherals{

    [[CBLECenterMnger shareMnger] cmdStartScan];
    [_scanTimeOut invalidate];
    _scanTimeOut = nil;
    _scanTimeOut = [NSTimer timerWithTimeInterval:20 target:self selector:@selector(scanTimeOutAction) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:_scanTimeOut forMode:NSRunLoopCommonModes];
}

- (void)scanTimeOutAction{
   
    [self stopScan];
    
    if ([[CBLECenterMnger shareMnger].dataPherals totalNums] == 0) {
//        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"没有发现设备".rh_localized];
       
    }else{
        
    }
    [self.tableView endHeaderRefresh];
    [self.tableView reloadData];
    [self.searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
    [self stopSearchAnimation];
    self.countLab.text = [NSString stringWithFormat:@"%@:%ld",@"数量".rh_localized,[CBLECenterMnger shareMnger].dataPherals.totalNums];
}



//停止扫描
- (void)stopScan{
 
    [_scanTimeOut invalidate];
    _scanTimeOut = nil;
    [[CBLECenterMnger shareMnger] cmdStopScan];
}


-(void)msgForBLEPowerOn{
   
    // 关闭状态
    if ([CBLECenterMnger BLEIsPowerOff] ) {
        [self stopScan];
        [self stopSearchAnimation];
        [self.searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
        [self.tableView reloadData];
    } else {
        if (![[CBLECenterMnger shareMnger] isScaning]){
            [self scanDevice];
        }
    }
}

-(void)msgForNewPheral{
   
    self.countLab.text = [NSString stringWithFormat:@"%@:%ld",@"数量".rh_localized,[CBLECenterMnger shareMnger].dataPherals.totalNums];
   [self.tableView reloadData];
}

-(void)msgForPheralConnect{
    //取消所有链接超时等待
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [SVProgressHUD dismiss];
    if(self.receiveMsg == NO) return;
    //蓝牙设备连接上
    if ([[CBLECenterMnger shareMnger] isConnectOK]){
      
        RHLocalDeviceVC *deviceVC = [[RHLocalDeviceVC alloc]init];
        deviceVC.title = [CBLECenterMnger shareMnger].curPheral.devName;
        [self.navigationController pushViewController:deviceVC animated:YES];
        //保存本地
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[CDataPheralMnger dataMnger] saveBleDevice:[CBLECenterMnger shareMnger].curPheral];
        });
        
    }else{

        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"socket connect failed!"];
    }
}

-(void)msgForPheralReConnect:(NSNotification*)no
{
   
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    return [CBLECenterMnger shareMnger].dataPherals.totalNums;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    RHBleScanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHBleScanCell"];
    CDataPheralInfo *data = [[CBLECenterMnger shareMnger].dataPherals dataWithIndex:indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.dataInfo = data;
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if ([CBLECenterMnger BLEIsPowerOff]) {
        [QMUITips showInfo:@"请打开蓝牙!".rh_localized];
        return;
    }
    //360K模组不让连接
    CDataPheralInfo *pheral = [[CBLECenterMnger shareMnger].dataPherals dataWithIndex:indexPath.row];
    if(pheral.wifiType == DevWiFiType360K){
        [QMUITips showInfo:@"不支持此功能".rh_localized];
        return;
    }
    [[CBLECenterMnger shareMnger]cmdStopScan];
    [self stopSearchAnimation];
    [self.searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
    [[CBLECenterMnger shareMnger] cmdConnect2Pheral:pheral];
    
}


@end
